package demo.reflect;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @ClassName MethodCollector
 * @Description
 * @Author 47980
 * @Date 2020/6/11 5:27
 * @Version V_1.0
 **/
public class MethodCollector {

    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        //1. 获取Class对象
        Class<?> clazz = Class.forName("demo.reflect.ReflectTarget");

        //2. 获取所有公有方法
        System.out.println("================= 获取所有公有方法 =================");
        Method[] methods = clazz.getMethods();
        for (Method method : methods) {
            System.out.println(method);
        }

        //3. 获取所有方法
        System.out.println("================= 获取所有方法 =================");
        Method[] declaredMethods = clazz.getDeclaredMethods();
        for (Method declaredMethod : declaredMethods) {
            System.out.println(declaredMethod);
        }

        //4. 获取单个公有方法
        System.out.println("================= 获取单个公有方法 =================");
        Method show1 = clazz.getMethod("show1", String.class);
        System.out.println(show1);
        //5. 调用show1方法并执行
        ReflectTarget reflectTarget = (ReflectTarget) clazz.getConstructor().newInstance();
        show1.invoke(reflectTarget, "待反射方法一号");

        //6. 获取一个私有的成员方法
        System.out.println("================= 获取一个私有的成员方法 =================");
        Method show4 = clazz.getDeclaredMethod("show4", String.class, int.class);
        System.out.println(show4);
        //7. 调用show4方法并执行
        show4.setAccessible(true);
        String show4Res = (String) show4.invoke(reflectTarget, "代反射方法四号", 10086);
        System.out.println(show4Res);
    }
}
